'use strict';

const BaseService = require('../base');

class TravelOrderItemService extends BaseService {
  static get modelName() {
    return 'Business.TravelOrderItem';
  }

  /**
   * 根据旅游订单ID获取订单项列表
   * @param {number} travelOrderId - 旅游订单ID
   * @return {Promise<Array>}
   */
  async getItemsByTravelOrder(travelOrderId) {
    const { ctx } = this;
    const items = await ctx.model.Business.TravelOrderItem.findAll({
      where: {
        travel_order_id: travelOrderId,
        is_deleted: 0
      },
      include: [
        {
          model: ctx.model.Business.Travel,
          as: 'travel',
          attributes: ['id', 'name', 'cover', 'description']
        },
        {
          model: ctx.model.Business.TravelSku,
          as: 'travelSku',
          attributes: ['id', 'spec_combination', 'price', 'stock']
        }
      ],
      order: [['create_time', 'DESC']]
    });
    return items;
  }

  /**
   * 批量创建旅游订单项
   * @param {Object} data - 订单项数据
   * @return {Promise<Array>}
   */
  async batchCreate(data) {
    const { ctx } = this;
    const { travel_order_id, items } = data;
    
    if (!travel_order_id || !items || !Array.isArray(items)) {
      throw new Error('参数错误');
    }

    const transaction = await ctx.model.transaction();
    try {
      const createdItems = [];
      for (const item of items) {
        const createdItem = await ctx.model.Business.TravelOrderItem.create({
          travel_order_id,
          travel_id: item.travel_id,
          travel_sku_id: item.travel_sku_id,
          travel_name: item.travel_name,
          travel_cover: item.travel_cover,
          sku_spec: item.sku_spec,
          price: item.price,
          count: item.count,
          total_amount: item.price * item.count
        }, { transaction });
        createdItems.push(createdItem);
      }
      
      await transaction.commit();
      return createdItems;
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }

  /**
   * 获取旅游订单项详情（包含旅游产品信息）
   * @param {number} id - 订单项ID
   * @return {Promise<Object>}
   */
  async getDetailWithTravel(id) {
    const { ctx } = this;
    const item = await ctx.model.Business.TravelOrderItem.findOne({
      where: {
        id,
        is_deleted: 0
      },
      include: [
        {
          model: ctx.model.Business.Travel,
          as: 'travel',
          attributes: ['id', 'name', 'cover', 'description', 'category_id']
        },
        {
          model: ctx.model.Business.TravelSku,
          as: 'travelSku',
          attributes: ['id', 'spec_combination', 'price', 'stock']
        },
        {
          model: ctx.model.Business.TravelOrder,
          as: 'travelOrder',
          attributes: ['id', 'order_no', 'status', 'amount']
        }
      ]
    });
    
    if (!item) {
      throw new Error('订单项不存在');
    }
    
    return item;
  }

  /**
   * 获取旅游订单项统计信息
   * @param {number} travelOrderId - 旅游订单ID
   * @return {Promise<Object>}
   */
  async getTravelOrderStatistics(travelOrderId) {
    const { ctx } = this;
    const { Op } = ctx.model.Sequelize;
    
    const items = await ctx.model.Business.TravelOrderItem.findAll({
      where: {
        travel_order_id: travelOrderId,
        is_deleted: 0
      },
      attributes: [
        'travel_id',
        'travel_name',
        [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('count')), 'total_count'],
        [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('total_amount')), 'total_amount']
      ],
      group: ['travel_id', 'travel_name']
    });

    const totalAmount = await ctx.model.Business.TravelOrderItem.sum('total_amount', {
      where: {
        travel_order_id: travelOrderId,
        is_deleted: 0
      }
    });

    const totalCount = await ctx.model.Business.TravelOrderItem.sum('count', {
      where: {
        travel_order_id: travelOrderId,
        is_deleted: 0
      }
    });

    return {
      items,
      total_amount: totalAmount || 0,
      total_count: totalCount || 0,
      item_count: items.length
    };
  }
}

module.exports = TravelOrderItemService; 